package br.com.seosoft.simplecalcfinan.fragmentos;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import br.com.seosoft.simplecalcfinan.Ed_Contas;
import br.com.seosoft.simplecalcfinan.R;
import br.com.seosoft.simplecalcfinan.geral;
import br.com.seosoft.simplecalcfinan.adapters.ListaAdapterContas;
import br.com.seosoft.simplecalcfinan.bancoDados.BancoDados;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragment;
import com.google.android.gms.ads.AdView;

public class FragContas extends SherlockFragment {

	public static final String PAGINA_MES = "pagina_mes";
	public static final String PAGINA_ANO = "pagina_ano";
	public static final String PAGINA_FK_GRUPO = "pagina_fk_grupo";
	public static final String PAGINA_ORDENAR_VALOR = "pagina_ordenar_valor";
	public static final String PAGINA_POSITION_PASTA = "pagina_position_pasta";

	private ListView list;
	private int[] id;
	private String fk_grupo = null;
	private String[] descricao;
	private BigDecimal[] saldo;
	private Date[] data;
	private int codigo = 1;
	private String descricao_grupo;
	private AdView adView;
	private String position_pasta;
	private static SharedPreferences preference;
	private SharedPreferences.Editor editor;
	private ActionBar actionbar;
	private ArrayAdapter<String> adapterListaAnos;
	private Bundle bl;
	private int mes;
	private int ano;
	private boolean ordenarValor;
	LinearLayout layoutVazio;
	ProgressBar progress;
	private ListarContasThread buscarContasThead;
	CallbackTotalMes callback;

	private boolean ordenarAsc;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.contas_pager, container,
				false);

		getIntent();

		return rootView;
	}

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);

		callback = (CallbackTotalMes) activity;
	}

	private void getIntent() {
		// TODO Auto-generated method stub
		// pega o mes e ano passado por intent
		bl = getArguments();
		if (bl != null) {

			mes = bl.getInt(PAGINA_MES);
			ano = bl.getInt(PAGINA_ANO);
			fk_grupo = bl.getString(PAGINA_FK_GRUPO);
			ordenarValor = bl.getBoolean(PAGINA_ORDENAR_VALOR);
			position_pasta = bl.getString(PAGINA_POSITION_PASTA);
		}
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewCreated(view, savedInstanceState);

		// PEGA A LISTA
		list = (ListView) getView().findViewById(R.id.list);
		layoutVazio = (LinearLayout) getView().findViewById(R.id.layoutVazio);
		progress = (ProgressBar) getView().findViewById(R.id.pbContasPb);

		if (ordenarValor) {
			buscarContasValor(true);
		} else {
			buscarContas(false);
		}

		registerForContextMenu(list);

	}

	public void buscarContas(boolean ordenarValor) {

		buscarContasThead = new ListarContasThread();
		buscarContasThead.execute(ordenarValor);

	}


	public void buscarContasValor(boolean ordenarValorAsc) {

		this.ordenarAsc = ordenarValorAsc;
		
		if (preference == null) {
			preference = PreferenceManager.getDefaultSharedPreferences(getActivity());
		}
		this.ordenarAsc = preference.getBoolean(geral.ORDENAR_SQL_VALOR, true);
		
		Log.i(geral.LogCat, "Ordenar valor ASC:"+ordenarValorAsc);
		buscarContasThead = new ListarContasThread();
		buscarContasThead.execute(true);

	}

	public void toggleProgressBar() {

		if (layoutVazio.getVisibility() == View.VISIBLE) {
			layoutVazio.setVisibility(View.GONE);
			progress.setVisibility(View.GONE);
			list.setVisibility(View.VISIBLE);
		} else {
			layoutVazio.setVisibility(View.VISIBLE);
			list.setVisibility(View.GONE);
			progress.setVisibility(View.VISIBLE);
		}

	}

	// EDITAR REGISTRO GRUPO
	public void editarRegistro(String id, String desc, BigDecimal _valor,
			String fk_grupo, Long _data) {
		final Intent itGrupos = new Intent(getActivity(), Ed_Contas.class);
		itGrupos.putExtra("acao", "editar");
		itGrupos.putExtra("position_pasta", position_pasta);
		itGrupos.putExtra("id_conta", id);
		itGrupos.putExtra("descricao_conta", desc);
		itGrupos.putExtra("saldo", _valor.toString());
		itGrupos.putExtra("fk_grupo", fk_grupo);
		itGrupos.putExtra("data", _data);
		startActivityForResult(itGrupos, codigo);
	}

	// cria o menu de contexto

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle(R.string.Opcoes);
		menu.add(0, 1, 0, R.string.editar);
		menu.add(0, 2, 0, R.string.Excluir);
		menu.add(0, 4, 0, R.string.replicar);
		menu.add(0, 3, 0, R.string.cancel);

	}

	//
	BancoDados bd;
	String _id;
	String _desc;
	BigDecimal _valor;
	Date _data;

	@Override
	public boolean onContextItemSelected(android.view.MenuItem item) {
		// TODO Auto-generated method stub
		bd = new BancoDados(getActivity(), true);
		// Corrige erro de criacao do menu de contexto em viewpagers
		if (getUserVisibleHint() == false) {
			return false;
		}

		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		_id = Integer.toString(id[info.position]);
		_desc = descricao[info.position];
		_valor = saldo[info.position];
		_data = data[info.position];

		// Registra o Alert Dialog
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setMessage(getResources().getString(R.string.Excluir) + " "
				+ _desc + " ?");
		builder.setCancelable(false);

		builder.setPositiveButton(R.string.sim,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// put your code here
						bd.DeletarRegistroContas(_id);

						buscarContas(false);

					}
				});
		builder.setNegativeButton(R.string.nao,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// put your code here
						dialog.cancel();
					}
				});
		AlertDialog alertDialog = builder.create();

		Log.e(geral.LogCat, "Item selecinado: " + item.getItemId()
				+ " Lista selecionada: " + info.position + ": "
				+ id[info.position]);

		SimpleDateFormat formatar = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
				Locale.getDefault());

		switch (item.getItemId()) {

		case 0:
			break;
		case 1:

			if (_data != null) {
				editarRegistro(_id, _desc, _valor, fk_grupo, _data.getTime());

			} else {
				editarRegistro(_id, _desc, _valor, fk_grupo, Long.valueOf(0));

			}
			Log.v(geral.LogCat, "DATA Editar: " + _id);
			Log.v(geral.LogCat, "DATA Editar: " + _desc);
			Log.v(geral.LogCat, "DATA Editar: " + _valor);
			Log.v(geral.LogCat, "DATA Editar: " + fk_grupo);
			Log.v(geral.LogCat, "DATA Editar: " + _data.getTime());
			break;
		case 2:
			alertDialog.show();
			break;
		case 4:

			if (_data != null) {
				bd.GravaRegistroContas(fk_grupo, _desc, String.valueOf(_valor),
						formatar.format(_data).toString());
				Log.v(geral.LogCat, "DATA Replicar: " + _data);
			} else {
				bd.GravaRegistroContas(fk_grupo, _desc, String.valueOf(_valor),
						null);
				Log.v(geral.LogCat, "DATA Replicar: " + _data);
			}

			new ListarContasThread().execute(false);
			break;
		default:

			break;
		}

		return true;

	}

	class ListarContasThread extends AsyncTask<Boolean, Void, List<geral>> {

		double aux = 0;
		double total = 0;
		BigDecimal aux2, total2;
		SimpleDateFormat formatar;
		List<geral> geralList = new ArrayList<geral>();
		BancoDados bd;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			total2 = new BigDecimal(0);
			toggleProgressBar();


			bd = new BancoDados(getActivity(), true);
			bd.setPreference(preference);
		}

		@Override
		protected List<geral> doInBackground(Boolean... params) {
			// TODO Auto-generated method stub

			if (params[0] == true) {
				bd.BuscaTodosRegistrosContasOrderValor(fk_grupo, mes, ano,
						ordenarAsc);
			} else {
				bd.BuscaTodosRegistrosContas(fk_grupo, mes, ano);
			}

			id = new int[bd.TotalRegistroContas()];
			descricao = new String[bd.TotalRegistroContas()];
			saldo = new BigDecimal[bd.TotalRegistroContas()];
			data = new Date[bd.TotalRegistroContas()];

			for (int i = 0; i < bd.TotalRegistroContas(); i++) {

				if (!isCancelled()) {

					bd.ProximoRegistroContas();
					Log.e(geral.LogCat, "LOOP ID_CONTA: " + id[i]);
					// inicia o vetor com o total de registros

					geral geral = new geral();
					geral.setIdConta(bd.c.getInt(0));
					// geral.setFkGrupo(bd.c.getString(1));
					geral.setDescConta(bd.c.getString(2));
					geral.setSaldoConta(bd.c.getDouble(3));

					id[i] = geral.getIdConta();
					// fk_grupo = geral.getFkGrupo();
					descricao[i] = geral.getDescConta();
					saldo[i] = new BigDecimal(bd.c.getString(3));

					if (bd.c.getString(4) != null) {

						try {

							formatar = new SimpleDateFormat(
									"dd/MM/yyyy HH:mm:ss", Locale.getDefault());

							data[i] = formatar.parse(bd.c.getString(4));
							Log.i(geral.LogCat, "DATA conta 1: " + data[i]);
							geral.setData(data[i]);
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							formatar = null;
							Log.e(geral.LogCat,
									"Erro DATA Conta 1: " + e.getMessage());
							data[i] = null;
						}
						try {
							formatar = new SimpleDateFormat("yyyy-MM-dd",
									Locale.getDefault());

							data[i] = formatar.parse(bd.c.getString(4));
							geral.setData(data[i]);
							Log.i(geral.LogCat, "DATA conta 3: " + data[i]);
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							Log.e(geral.LogCat,
									"Erro DATA Conta 3: " + e.getMessage());

							formatar = null;
						}

					} else {
						data[i] = null;
					}

					geralList.add(geral);

					// Adiciona cada valor e soma o total
					aux = Double.valueOf(geral.getSaldoConta());
					aux2 = new BigDecimal(bd.c.getString(3));
					total2 = total2.add(aux2);

					total = aux + total;
					Log.e(br.com.seosoft.simplecalcfinan.geral.LogCat, "Aux: "
							+ aux2.doubleValue());
					Log.e(br.com.seosoft.simplecalcfinan.geral.LogCat,
							"Total: " + total2.doubleValue());
				} else {

					return null;
				}
			}

			return geralList;
		}

		@Override
		protected void onPostExecute(List<geral> result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			// VALOR TOTAL DAS CONTAS NO TEXT VIEW
			bd.fechar();
			Log.e(br.com.seosoft.simplecalcfinan.geral.LogCat, "Total Conta: "
					+ total2.doubleValue());

			if (!isCancelled()) {

				callback.onTotalMes(mes, total2.doubleValue());

				ListaAdapterContas adapter = new ListaAdapterContas(
						getActivity(), result);

				list.setAdapter(adapter);
				toggleProgressBar();
			}

		}

	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub

		buscarContasThead.cancel(true);
		super.onDestroy();
	}


	public interface CallbackTotalMes {

		public void onTotalMes(int mes, Double total);

	}
}
